package com.maxdu.labs.stt.activities;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stt.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.maxdu.labs.stt.constants.Constants;
import com.maxdu.labs.stt.models.TPlan;
import com.maxdu.labs.stt.models.Training;
import com.maxdu.labs.stt.models.TrainingType;
import com.maxdu.labs.stt.models.db.TPlanDBHelper;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;

public class AddTrainingActivity extends Activity {

	private String currentUserId;
	private Button typeClimbingBtn;
	private Button typeRunningBtn;
	private Button todayBtn;
	private Button yesterdayBtn;
	private Button dayBeforeYesterdayBtn;
	private Button moreBtn;
	private int trainingTypeResult = -1;
	private LinearLayout whenLayout;
	private TPlan tplan;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_add_training);
		
		//addADummyTraining();
		
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        if(bundle!=null)
        {
            tplan =(TPlan) bundle.get("tplan");
            if(tplan != null){
	            	
	            	Log.d(Constants.LOG_TAG,"tplanId == " + tplan.getId());
			
			    // Check for an open session
			    final Session session = Session.getActiveSession();
			    if (session != null && session.isOpened()) {
			        // Get the user's data
			        makeMeRequest(session);
			    }
			    
			    typeClimbingBtn = (Button)findViewById(R.id.btn_type_climbing);
			    typeRunningBtn = (Button)findViewById(R.id.btn_type_running);
			    whenLayout = (LinearLayout)findViewById(R.id.layout_when);
			    
			    typeClimbingBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						trainingTypeResult = TrainingType.TYPE_CLIMBING;
						typeClimbingBtn.setBackgroundColor(Color.GREEN);
						typeRunningBtn.setBackgroundColor(Color.GRAY);
						whenLayout.setVisibility(View.VISIBLE);
						
						activateStep2();
					}
				});
			    typeRunningBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						trainingTypeResult = TrainingType.TYPE_RUNNING;
						typeRunningBtn.setBackgroundColor(Color.GREEN);
						typeClimbingBtn.setBackgroundColor(Color.GRAY);
						whenLayout.setVisibility(View.VISIBLE);
						
						activateStep2();
					}
				});
            }else{
            	TextView somethingWentWrong = (TextView)findViewById(R.id.tv_something_went_wrong);
            	somethingWentWrong.setVisibility(View.VISIBLE);
            	Log.e(Constants.LOG_TAG,"AddTrainingActivity :: tplan object isnt in the bundle");
            }
        }else{
        	TextView somethingWentWrong = (TextView)findViewById(R.id.tv_something_went_wrong);
        	somethingWentWrong.setVisibility(View.VISIBLE);
        	Log.e(Constants.LOG_TAG,"AddTrainingActivity :: can't find the tplan object from bundle :: bundle is NULL");
        }
	}
	
	private void makeMeRequest(final Session session) {
	    // Make an API call to get user data and define a 
	    // new callback to handle the response.
	    Request request = Request.newMeRequest(session, 
	            new Request.GraphUserCallback() {
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	            // If the response is successful
	            if (session == Session.getActiveSession()) {
	                if (user != null) {
	                    currentUserId = user.getId();
	                }
	            }
	            if (response.getError() != null) {
	                // Handle errors, will do so later.
	            }
	        }
	    });
	    request.executeAsync();
	} 
	
	//TODEL 
	private void addADummyTraining(){
		String trainingTMPId = "training1";
		
		ParseQuery<ParseObject> query = ParseQuery.getQuery(TPlanDBHelper.PARSE_DB_TABLENAME_TPLAN);
	query.whereEqualTo(TPlanDBHelper.PARSE_DB_FIELD_TPLANID,trainingTMPId);
	
	query.findInBackground(new FindCallback<ParseObject>() {
	    public void done(List<ParseObject> trainingsPO, ParseException e) {
	        if (e == null) {
	        	if (trainingsPO != null && trainingsPO.size()> 0){
	        		for (ParseObject trainingPO : trainingsPO){
	        			TPlan _training = new TPlan(trainingPO.getString(TPlanDBHelper.PARSE_DB_FIELD_TPLANID),
	        												trainingPO.getString(TPlanDBHelper.PARSE_DB_FIELD_NAME),
	        												trainingPO.getInt(TPlanDBHelper.PARSE_DB_FIELD_TYPE1),
	        												trainingPO.getInt(TPlanDBHelper.PARSE_DB_FIELD_DURATION),
	        												trainingPO.getInt(TPlanDBHelper.PARSE_DB_FIELD_FREQUENCY1));
	        			
	          			tplan = _training;
	        			
	        		}
	        	} else {
	        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the pendin;g FriendRequests for the current user: users list is EMPTY");
	        	}
	        } else {
	            Log.d(Constants.LOG_TAG, "Error: " + e.getMessage());
	        }
	    }
	});
	}

	private void activateStep2(){
		todayBtn = (Button)findViewById(R.id.btn_today);
		yesterdayBtn = (Button)findViewById(R.id.btn_yesterday);
		dayBeforeYesterdayBtn = (Button)findViewById(R.id.btn_day_before_yesterday);
		moreBtn = (Button)findViewById(R.id.btn_more);
		
		todayBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				saveTraining(Training.DAY_TODAY);
			}
		});
		yesterdayBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				saveTraining(Training.DAY_YESTERDAY);
			}
		});
		dayBeforeYesterdayBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				saveTraining(Training.DAY_DAY_BEFORE_YESTERDAY);
			}
		});
	}
	
	@SuppressLint("SimpleDateFormat") 
	private void saveTraining(int day){
		if(tplan != null && currentUserId != null && trainingTypeResult != -1){
			
			final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			final Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE, day);
			
			ParseObject trainingParseObject = new ParseObject(Training.PARSE_DB_TABLENAME);
			
			trainingParseObject.put(Training.PARSE_DB_FIELD_TPLANID, tplan.getId());
			trainingParseObject.put(Training.PARSE_DB_FIELD_USERID, currentUserId);
			trainingParseObject.put(Training.PARSE_DB_FIELD_DATE, cal.getTime().getTime());
			trainingParseObject.put(Training.PARSE_DB_FIELD_TRAINING_TYPE, trainingTypeResult);
			
			trainingParseObject.saveInBackground(new SaveCallback() {
				
				@Override
				public void done(ParseException e) {
					if (e == null){
						Log.d(Constants.LOG_TAG, "we successfully updated to Cloud the Training:  TPlan[" + tplan.getId() + "] - User [" + currentUserId + "] - day[" + dateFormat.format(cal.getTime()) );
			      		Toast.makeText(AddTrainingActivity.this, getResources().getString(R.string.training_added), Toast.LENGTH_LONG).show();
			  			Intent intent = new Intent(AddTrainingActivity.this, MainActivity.class);
			  			startActivity(intent);
					}else{
						Log.e(Constants.LOG_TAG, "we couldn't update to Cloud the Training:  TPlan[" + tplan.getId() + "] - User [" + currentUserId + "] - day[" + dateFormat.format(cal.getTime()) );
					}
					
				}
			});
		}else if (tplan == null){
			Log.e(Constants.LOG_TAG, "AddTrainingActivity::saveTraining() :: tplan is NULL ");
		}else if (currentUserId == null){
			Log.e(Constants.LOG_TAG, "AddTrainingActivity::saveTraining() :: currentUser is NULL ");
			//TODO should makeMeRequest again ..
		}else{
			Log.e(Constants.LOG_TAG, "AddTrainingActivity::saveTraining() :: trainingTypeResult == -1 ");
		}
	}
}
